import store from '@/store'
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import { RouteConfig } from 'vue-router'
import router, { constantRoutes, asyncRoutes, resetRouter } from '@/router'

/**
 *
 * @param names 路由name
 * @param route 路由表
 */
const hasPermission = (names: string[], route: RouteConfig) => {
    if (names.includes(route.name || route.path)) {
        return true
    }
}

export const filterAsyncRoutes = (routes: RouteConfig[], names: string[]) => {
    const res: RouteConfig[] = []
    routes.forEach((route) => {
        const r = { ...route }
        if (r.children?.length) {
            r.children = filterAsyncRoutes(r.children || [], names)
            if (r.children.length) {
                res.push(r)
            }
        } else {
            if (hasPermission(names, r)) {
                res.push(r)
            }
        }
    })
    return res
}

export interface IPermissionState {
    routes: RouteConfig[]
    dynamicRoutes: RouteConfig[]
}

@Module({ dynamic: true, store, name: 'permission' })
class Permission extends VuexModule implements IPermissionState {
    public routes: RouteConfig[] = []
    public dynamicRoutes: RouteConfig[] = []

    @Mutation
    private SET_ROUTES(routes: RouteConfig[]) {
        this.dynamicRoutes = routes
        this.routes = constantRoutes.concat(routes)
    }

    @Mutation
    RESET_ROUTES() {
        this.dynamicRoutes = []
        this.routes = []
    }

    @Action
    public GenerateRoutes(names: string[]) {
        let accesedRoutes = filterAsyncRoutes(asyncRoutes, names)
        this.SET_ROUTES(accesedRoutes)
        router.addRoutes(accesedRoutes)
    }

    @Action
    ResetRoutes() {
        this.RESET_ROUTES()
        resetRouter()
    }
}

export const PermissionModule = getModule(Permission)
